#!/usr/bin/env Rscript
library(GenomicRanges)
library(regioneR)
library(data.table)

#Create Input Paths from args
args = commandArgs(trailingOnly=TRUE)
Input.File<-paste(args[1],"Frag_BC_Corrected.txt", sep = "/")
Output.File<-paste(args[1],"BC_Corrected_Collapse.txt", sep = "/")

#Input File
BC_Bed<-fread(Input.File)
colnames(BC_Bed)<-c("Chr","Start","End","BC","Read")
BC_Bed.gr<-toGRanges(BC_Bed)



# Reduce overlaps
final <- unlist(reduce(split(BC_Bed.gr, BC_Bed.gr$BC),with.revmap=T))

df <- data.frame(BC=names(final), seqnames=seqnames(final), starts=start(final), ends=end(final), Count=lengths(final$revmap)) 
write.table(df, sep = "\t",Output.File, quote = F, row.names = F, col.names = F)
